package com.pig4cloud.pig.ads.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.pig.mapper.ProjectSettingsMapper;
import com.pig4cloud.pig.ads.service.ProjectSettingsService;
import com.pig4cloud.pig.api.dto.ProjectSettingsDto;
import com.pig4cloud.pig.api.entity.ProjectSettings;
import com.pig4cloud.pig.api.vo.ProjectSettingsVo;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @description:
 * @author: nml
 * @time: 2020/11/4 13:54
 **/
@Service
@RequiredArgsConstructor
public class ProjectSettingsServiceImpl extends ServiceImpl<ProjectSettingsMapper,ProjectSettings> implements ProjectSettingsService {

	@Autowired
	private ProjectSettingsMapper projectSettingsMapper;

	//查询所有，包括资源数
	@Override
	public IPage<ProjectSettingsDto> selectAll(ProjectSettingsVo req) {
		IPage<ProjectSettingsDto> projectSettingsDtos = projectSettingsMapper.selectAll(req);
		return projectSettingsDtos;
	}

	//修改
	@Override
	public R update(ProjectSettings req) {
		ProjectSettings projectSettings = projectSettingsMapper.selectByPrimaryKey(req.getId());
		if (req.getProjectName().equals(projectSettings.getProjectName())){
			int update = projectSettingsMapper.updateByPrimaryKeySelective(req);
			if (update == 1 ){
				return R.ok(1,"修改成功");
			}
			return R.failed(0,"修改失败");
		}else {
			//根据名称查询，判断该名称是否存在
			QueryWrapper<ProjectSettings> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("project_name",req.getProjectName());
			ProjectSettings projectSettings1 = projectSettingsMapper.selectOne(queryWrapper);
			if (Objects.isNull(projectSettings1)){
				req.setUpdateTime(new Date());
				int i = projectSettingsMapper.updateByPrimaryKeySelective(req);
				if (i == 1 ){
					return R.ok(1,"修改成功");
				}
				return R.failed(0,"修改失败");
			}
			return R.failed(0,"该项目名称已存在");
		}

	}

	//添加
	@Override
	public R add(ProjectSettings req) {
		//根据名称查询，判断该名称是否存在
		QueryWrapper<ProjectSettings> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(true,"project_name",req.getProjectName());
		ProjectSettings projectSettings = projectSettingsMapper.selectOne(queryWrapper);
		if (Objects.isNull(projectSettings)){
			req.setUpdateTime(new Date());
			int i = projectSettingsMapper.insertSelective(req);
			if (i==1){
				return R.ok(1,"添加成功");
			}
			return R.failed(0,"添加失败");
		}
		return R.failed(0,"该项目名称已存在");
	}

}
